<template>
  <view class="tutor-edit-container">
    <form @submit.prevent="handleSubmit" class="edit-form">
      <!-- 表单内容区 -->
      <view class="form-content">
        <!-- 姓名 -->
        <view class="form-group">
          <text class="form-label">姓名 *</text>
          <input type="text" class="form-input" v-model="formData.name" placeholder="请输入姓名" />
          <text class="form-tip" v-if="errors.name">{{ errors.name }}</text>
        </view>
        
        <!-- 性别 -->
        <view class="form-group">
          <text class="form-label">性别 *</text>
          <radio-group class="form-radio-group" v-model="formData.gender">
            <label class="radio-label">
              <radio value="1" /> 男
            </label>
            <label class="radio-label">
              <radio value="0" /> 女
            </label>
          </radio-group>
        </view>
        
        <!-- 年龄 -->
        <view class="form-group">
          <text class="form-label">年龄 *</text>
          <input type="number" class="form-input" v-model="formData.age" placeholder="请输入年龄" />
          <text class="form-tip" v-if="errors.age">{{ errors.age }}</text>
        </view>
        
        <!-- 星级 -->
        <view class="form-group">
          <text class="form-label">星级 *</text>
          <input type="number" class="form-input" v-model="formData.stars" placeholder="请输入星级" min="1" max="5" />
          <text class="form-tip" v-if="errors.stars">{{ errors.stars }}</text>
        </view>
        
        <!-- 体重 -->
        <view class="form-group">
          <text class="form-label">体重 *</text>
          <input type="number" class="form-input" v-model="formData.weight" placeholder="请输入体重(kg)" />
          <text class="form-tip" v-if="errors.weight">{{ errors.weight }}</text>
        </view>
        
        <!-- 身高 -->
        <view class="form-group">
          <text class="form-label">身高 *</text>
          <input type="number" class="form-input" v-model="formData.height" placeholder="请输入身高(cm)" />
          <text class="form-tip" v-if="errors.height">{{ errors.height }}</text>
        </view>
        
        <!-- 价格 -->
        <view class="form-group">
          <text class="form-label">价格 *</text>
          <input type="number" class="form-input" v-model="formData.price" placeholder="请输入价格" />
          <text class="form-tip" v-if="errors.price">{{ errors.price }}</text>
        </view>
        
        <!-- 毕业院校 -->
        <view class="form-group">
          <text class="form-label">毕业院校 *</text>
          <input type="text" class="form-input" v-model="formData.school" placeholder="请输入毕业院校" />
          <text class="form-tip" v-if="errors.school">{{ errors.school }}</text>
        </view>
        
        <!-- 籍贯 -->
        <view class="form-group">
          <text class="form-label">籍贯 *</text>
          <input type="text" class="form-input" v-model="formData.birthplace" placeholder="请输入籍贯" />
          <text class="form-tip" v-if="errors.birthplace">{{ errors.birthplace }}</text>
        </view>
        
        <!-- 自我介绍 -->
        <view class="form-group">
          <text class="form-label">自我介绍 *</text>
          <textarea class="form-textarea" v-model="formData.content" placeholder="请输入自我介绍" rows="4"></textarea>
          <text class="form-tip" v-if="errors.content">{{ errors.content }}</text>
        </view>
        
        <!-- 单个图片上传 (简化版) -->
        <view class="form-group">
          <text class="form-label">个人照片</text>
          <view class="upload-area" @click="chooseImage">
            <text>点击选择图片</text>
          </view>
          <text class="form-tip">单个图片（选填）</text>
        </view>
        
        <!-- 图片列表上传 (简化版) -->
        <view class="form-group">
          <text class="form-label">照片集</text>
          <view class="upload-area" @click="chooseImages">
            <text>点击选择多张图片</text>
          </view>
          <text class="form-tip">多张图片（选填）</text>
        </view>
        
        <!-- 视频上传 (简化版) -->
        <view class="form-group">
          <text class="form-label">视频</text>
          <view class="upload-area" @click="chooseVideo">
            <text>点击选择视频</text>
          </view>
          <text class="form-tip">单个视频（选填）</text>
        </view>
      </view>
      
      <!-- 提交区域 -->
      <view class="submit-section">
        <button type="primary" class="submit-btn" :disabled="submitting" @click="handleSubmit">{{ submitting ? '提交中...' : '提交' }}</button>
      </view>
    </form>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 表单数据
      formData: {
        id: '',
        name: '',
        image: '',
        images: [],
        video: '',
        gender: '1',
        age: '',
        stars: '1',
        weight: '',
        height: '',
        content: '',
        school: '',
        birthplace: '',
        price: ''
      },
      // 错误信息
      errors: {},
      // 提交状态
      submitting: false
    };
  },
  onLoad(options) {
    if (options.id) {
      this.formData.id = options.id;
      this.getTutorDetail(options.id);
    }
  },
  methods: {
    // 获取助教详情（编辑模式）
    async getTutorDetail(id) {
      try {
        const res = await this.$request({
          url: '/tutor/detail',
          method: 'GET',
          params: {
            ids: id
          }
        });
        
        if (res.code === 1) {
          const data = res.data;
          this.formData = {
            id: data.id,
            name: data.name || '',
            image: data.image || '',
            images: data.images || [],
            video: data.video || '',
            gender: String(data.gender || 1),
            age: data.age || '',
            stars: String(data.stars || 1),
            weight: data.weight || '',
            height: data.height || '',
            content: data.content || '',
            school: data.school || '',
            birthplace: data.birthplace || '',
            price: data.price || ''
          };
        } else {
          throw new Error(res.msg || '获取助教详情失败');
        }
      } catch (error) {
        console.error('获取助教详情失败:', error);
        uni.showToast({
          title: error.message || '获取助教详情失败',
          icon: 'none'
        });
        // 返回上一页
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      }
    },
    
    // 表单验证
    validateForm() {
      this.errors = {};
      let isValid = true;
      
      if (!this.formData.name.trim()) {
        this.errors.name = '请输入姓名';
        isValid = false;
      }
      
      if (!this.formData.age || isNaN(this.formData.age) || this.formData.age < 18 || this.formData.age > 60) {
        this.errors.age = '请输入18-60之间的年龄';
        isValid = false;
      }
      
      if (!this.formData.stars || isNaN(this.formData.stars) || this.formData.stars < 1 || this.formData.stars > 5) {
        this.errors.stars = '请输入1-5之间的星级';
        isValid = false;
      }
      
      if (!this.formData.weight || isNaN(this.formData.weight) || this.formData.weight <= 0) {
        this.errors.weight = '请输入有效的体重';
        isValid = false;
      }
      
      if (!this.formData.height || isNaN(this.formData.height) || this.formData.height <= 0) {
        this.errors.height = '请输入有效的身高';
        isValid = false;
      }
      
      if (!this.formData.price || isNaN(this.formData.price) || this.formData.price < 0) {
        this.errors.price = '请输入有效的价格';
        isValid = false;
      }
      
      if (!this.formData.school.trim()) {
        this.errors.school = '请输入毕业院校';
        isValid = false;
      }
      
      if (!this.formData.birthplace.trim()) {
        this.errors.birthplace = '请输入籍贯';
        isValid = false;
      }
      
      if (!this.formData.content.trim()) {
        this.errors.content = '请输入自我介绍';
        isValid = false;
      }
      
      return isValid;
    },
    
    // 提交表单
    async handleSubmit() {
      // 验证表单
      if (!this.validateForm()) {
        return;
      }
      
      try {
        this.submitting = true;
        const url = '/tutor/profile';
        const method = 'POST';
        
        // 准备提交数据
        const data = {
          name: this.formData.name,
          gender: this.formData.gender,
          age: this.formData.age,
          stars: this.formData.stars,
          weight: this.formData.weight,
          height: this.formData.height,
          content: this.formData.content,
          school: this.formData.school,
          birthplace: this.formData.birthplace,
          price: this.formData.price
        };
        
        // 如果是编辑模式，需要添加id
        if (this.formData.id) {
          data.ids = this.formData.id;
        }
        
        // 注意：图片和视频上传需要单独处理，这里简化了
        // 实际项目中应该调用uni.uploadFile等API上传文件
        if (this.formData.image) {
          data.image = this.formData.image;
        }
        if (this.formData.images && this.formData.images.length > 0) {
          data.images = this.formData.images;
        }
        if (this.formData.video) {
          data.video = this.formData.video;
        }
        
        const res = await this.$request({
          url,
          method,
          data
        });
        
        if (res.code === 1) {
          uni.showToast({
            title: this.formData.id ? '编辑成功' : '添加成功',
            icon: 'success'
          });
          
          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          throw new Error(res.msg || (this.formData.id ? '编辑失败' : '添加失败'));
        }
      } catch (error) {
        console.error(this.formData.id ? '编辑助教失败:' : '添加助教失败:', error);
        uni.showToast({
          title: error.message || (this.formData.id ? '编辑失败' : '添加失败'),
          icon: 'none'
        });
      } finally {
        this.submitting = false;
      }
    },
    
    // 选择单个图片（简化版）
    chooseImage() {
      uni.chooseImage({
        count: 1,
        success: (res) => {
          // 实际项目中应该上传图片并获取图片URL
          this.formData.image = res.tempFilePaths[0];
          // 这里只是模拟，实际需要调用上传API
          console.log('选择的图片:', res.tempFilePaths[0]);
        }
      });
    },
    
    // 选择多个图片（简化版）
    chooseImages() {
      uni.chooseImage({
        count: 9,
        success: (res) => {
          // 实际项目中应该上传图片并获取图片URL数组
          this.formData.images = res.tempFilePaths;
          // 这里只是模拟，实际需要调用上传API
          console.log('选择的多张图片:', res.tempFilePaths);
        }
      });
    },
    
    // 选择视频（简化版）
    chooseVideo() {
      uni.chooseVideo({
        success: (res) => {
          // 实际项目中应该上传视频并获取视频URL
          this.formData.video = res.tempFilePath;
          // 这里只是模拟，实际需要调用上传API
          console.log('选择的视频:', res.tempFilePath);
        }
      });
    }
  }
};
</script>

<style scoped>
.tutor-edit-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding: 20rpx;
}

/* 表单内容区 */
.form-content {
  background-color: #fff;
  border-radius: 15rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

/* 表单组 */
.form-group {
  margin-bottom: 30rpx;
}

.form-group:last-child {
  margin-bottom: 0;
}

/* 表单标签 */
.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
}

/* 表单输入框 */
.form-input {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #333;
  box-sizing: border-box;
}

/* 表单文本域 */
.form-textarea {
  width: 100%;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #333;
  box-sizing: border-box;
  min-height: 200rpx;
}

/* 表单提示 */
.form-tip {
  display: block;
  font-size: 24rpx;
  color: #ff3b30;
  margin-top: 6rpx;
}

/* 单选组 */
.form-radio-group {
  display: flex;
  gap: 40rpx;
  padding: 20rpx 0;
}

.radio-label {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: #333;
}

/* 上传区域 */
.upload-area {
  width: 100%;
  height: 160rpx;
  border: 1rpx dashed #ddd;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #999;
  background-color: #f9f9f9;
}

/* 提交区域 */
.submit-section {
  margin-top: 30rpx;
  padding: 0 30rpx;
}

/* 提交按钮 */
.submit-btn {
  width: 100%;
  height: 90rpx;
  background-color: #4cd964;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  font-size: 32rpx;
  font-weight: bold;
}

.submit-btn:disabled {
  opacity: 0.6;
}
</style>